package mongo;

import com.mongodb.*;
import net.sf.json.JSONObject;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.*;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * USER: lintc 【lintiancong@zhuojianchina.com】
 * DATE: 2017-03-06 16:18
 */
public class SpringMongo {

    static MongoCredential apiFlowCredential = MongoCredential.createCredential("zfh", "api_flow", "zfh666".toCharArray());

    static MongoCredential apiWarningCredential = MongoCredential.createCredential("zfh", "api_warning", "zfh666".toCharArray());

    static MongoCredential testCredential = MongoCredential.createCredential("zfh", "test", "zfh666".toCharArray());

    public static Mongo mongo = new MongoClient(new ServerAddress("192.168.0.216", 27017), Arrays.asList(apiFlowCredential, apiWarningCredential, testCredential));

    public static MongoTemplate mongoTemplate = new MongoTemplate(mongo, "api_flow");

    public static MongoTemplate mongoTemplate2 = new MongoTemplate(mongo, "api_warning");

    public static MongoTemplate testTemplate = new MongoTemplate(mongo, "test");

    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        DBCollection collection = testTemplate.getCollection("db_movie");
        DBCursor dbCursor = collection.find(new BasicDBObject());
        while (dbCursor.hasNext()) {
            JSONObject obj = JSONObject.fromObject(dbCursor.next());
            set.add(obj.optString("url"));
        }
        System.out.println(set.size());
    }

    public static Set<String> getDbMovie() {
        Set<String> set = new ConcurrentSkipListSet<>();
        DBCollection collection = testTemplate.getCollection("db_movie");
        DBCursor dbCursor = collection.find(new BasicDBObject());
        while (dbCursor.hasNext()) {
            JSONObject obj = JSONObject.fromObject(dbCursor.next());
            set.add(obj.optString("url"));
        }
        return set;
    }

    public static void testMongodb() {
        // 连接mongo
        Mongo mongo = new Mongo("111.1.55.5", 27017);
        // 连接数据库
        DB db = mongo.getDB("test");
        // 获取表
        Set<String> collectionNames = db.getCollectionNames();
        for (String name : collectionNames) {
            System.out.println("name : " + name);
        }
    }

    public static void findObj() {
        DBObject obj = new BasicDBObject("topic", "app_shdsyy");
        obj.put("output.failure_reason", "@server cause an error");
        DBObject time = new BasicDBObject("$regex", "2017-03-08");
        time.put("$options", "i");
        obj.put("time", time);
        long start = System.currentTimeMillis();
        List<String> list = mongoTemplate.find(new BasicQuery(obj), String.class, "api_log");
        long end = System.currentTimeMillis();
        System.out.println(list.size() + " : " + (end - start));
        int i = 0;
        for (String object : list) {
//            ObjectId id = object.optString("_id");
            System.out.println((i ++) + object);
        }
    }

    /**
     * 获取抓取 elasticsearch 列表
     * @return
     */
    public static List<JSONObject> getCatchList() {
        List<JSONObject> list = mongoTemplate.find(new BasicQuery(new BasicDBObject()), JSONObject.class, "catch_list");
        return list;
    }

    public static void find() {
        MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new Mongo("111.1.55.5", 27017), "test"));
        JSONObject obj = mongoOps.findOne(Query.query(Criteria.where("topic").is("app_zyyy")), JSONObject.class, "api_log");
        System.out.println(obj);
    }

    /**
     * 聚合查询
     */
    public static void aggregation() {
        // 过滤条件 match
        DBObject match1 = new BasicDBObject("topic", "app_zyyy");
        match1.put("output.is_success", "0");
        DBObject match2 = new BasicDBObject("$regex", "2017-03-07");
        match2.put("$options", "i");
        match1.put("time", match2);
        DBObject match = new BasicDBObject("$match", match1);
        // 分组统计 group
        DBObject group1 = new BasicDBObject("_id", "$output.failure_reason");
        group1.put("num", new BasicDBObject("$sum", 1)); // 添加多个条件

        DBObject group = new BasicDBObject("$group", group1);
        List<DBObject> list = new ArrayList<>();
        list.add(match);
        list.add(group);
        AggregationOutput output = mongoTemplate.getCollection("api_log").aggregate(list);
//        AggregationOutput output = mongoTemplate.getCollection("orders").aggregate(match, new BasicDBObject(), group, new BasicDBObject());
        Iterator<DBObject> iterator = output.results().iterator();
        int i = 0;
        while (iterator.hasNext()) {
            System.out.println((i++) + " : " + iterator.next());
        }
    }
}
